/*
 * @Author: 扶苏
 * @Date: 2022年11月7日 10:11:02
 * @LastEditors: 扶苏
 * @LastEditTime:  2022年11月7日 10:11:02
 * @Description:
 */

import axios from "axios"
// 在main.js中放入这段自定义适配器的代码，就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求，并支持携带cookie
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require("axios/lib/core/settle")
		var buildURL = require("axios/lib/helpers/buildURL")
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.header,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config,
				}

				settle(resolve, reject, response)
			},
		})
	})

}
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	// baseURL: process.env.VUE_APP_BASE_API,
	baseURL: '地址',
	// 超时（毫秒）
	timeout: 10000
})
// import axiosAdapterUniapp from 'axios-adapter-uniapp' //axios 适配uniapp的工具
class HttpRequest {
	constructor(baseUrl) {
		this.baseUrl = baseUrl
		this.flag = false //是否退出登录标志
	}
	getInsideConfig() {
		const config = {
			baseURL: this.baseUrl,
			// adapter: axiosAdapterUniapp,
			header: {
				// token: uni.getStorageSync("token") || ''
			}
		}
		return config
	}
	interceptors(instance) {
		// 请求拦截
		instance.interceptors.request.use(
			config => {
				let TOKEN = uni.getStorageSync("token") || ""
				if (TOKEN) {
					config.header["token"] = TOKEN
				} else {
					this.flag = false //重置登录标志
				}
				return config
			},
			error => {
				return Promise.reject(error)
			}
		)
		// 响应拦截
		instance.interceptors.response.use(
			res => {
				let token = res.header.token || ""
				if (token) {
					uni.setStorageSync("token", token) //更新token
				}
				const {
					data,
					status,
					header
				} = res
				return {
					data,
					status,
					header,
				}

			},
			error => {
				return Promise.reject(error)
			}
		)
	}
	request(options) {
		const instance = axios.create()
		options = Object.assign(this.getInsideConfig(), options)
		this.interceptors(instance, options.url)
		return instance(options)
	}
}
export default HttpRequest
